<!-- 鼠标右键弹出的盒子 -->
<template>
  <!-- 全局 dialog -->
  <div class="os-dialog-fox" :class="isPreview ? '' : 'hide-dialog'"> 
    <el-dialog class="os-dialog" v-model="dialogVisible" title="确认处方" width="595" :append-to-body="isPreview">
      <div ref="prescriptionRef" class="prescription-container">
        
        <div class="title">
          {{ userInfo.fixmedins_name }}
         <div class="type">{{ CirculationTypeName }}</div>  
        </div>
        <div class="prescription-info border-bottom-bold margin-bottom-sm">
          <div class="border-bottom-bold aicjcsb margin-bottom-sm padding-bottom">
            <div>开具时间： {{ detail.electronicPrescriptionTime.substr(0,10) }}</div>
            <div>处方编号：<span style="display: inline-block;min-width: 250px;">{{ detail.OnlineInquiryNo }}</span></div>
          </div>
          
          <div class="info-row aic">
            <div class="flex1 df">
              <span class="label">姓名：</span>
              <span class="value">{{detail.psn_name}}</span>
            </div>
            <div class="flex1 df">
              <span class="label">性别：</span>
              <span class="value">{{detail.sex == 2 ? '女' : '男'}}</span>
            </div>
            <div class="flex1 df">
              <span class="label">年龄：</span>
              <span class="value">{{detail.age}}</span>
            </div>
            <div class="flex1 df">
              <span class="label">诊断性质：</span>
              <span class="value">{{detail.diag_name}}</span>
            </div>
            <div class="flex1 df">
              <span class="label">科室：</span>
              <span class="value">{{detail.ks}}</span>
            </div>
            <div class="flex1 df">
              <span class="label">身份证号：</span>
              <span class="value">{{detail.mdtrt_cert_no}}</span>
            </div>
            <div class="flex1 df">
              <span class="label">ICD诊断：</span>
            <span class="value">{{detail.Symptom}}</span>
            </div>
          </div>
        </div>
        <h3 class="text-bold">Rp:</h3>
        <div class="prescription-medicine"  :class="detail.PrescriptionType == 1 ? '' : 'ch-prescription-medicine'">
          <div>
            <div :class="detail.PrescriptionType == 1 ? '' : 'ch-medicine'">
              <div class="item" v-for="(item,index) in medicineList" :key="index">
                <div class="df">
                  <div class="flex1 name">
                    <div>{{ item.ItemName }}</div>
                  </div>
                  <div class="flex1" v-if="detail.PrescriptionType == 1">
                    <div>
                      {{ item.spec }}
                    </div>
                  </div>
                  <div class="flex1 num">
                    <div>
                      <span>{{ item.DrugNum }}</span>
                      <span v-if="detail.PrescriptionType == 2">g</span>
                      <span v-else>{{ item.unt }}</span>
                    </div>
                  </div>
                </div>
                <div class="sig" v-if="detail.PrescriptionType != 2">
                  <strong>Sig:</strong> <span class="margin-right">{{ item.used_frqu_dscr }}</span>{{ item.usageDosage }}
                </div>
              </div>
            </div>
            
            
          </div>
          <div class="blank" v-if="medicineList.length < (detail.PrescriptionType == 1 ? 5 : 30)">
            <div class="blank-text">以下空白</div>
            <div class="bias-container">
              <div class="bias"></div>
            </div>
          </div>
        </div>
        <div class="sig" v-if="detail.PrescriptionType == 2">
          <strong>Sig:</strong> 总剂量{{medicineForm.cmDrugNum}}g <span class="margin-left">{{ medicineForm.cmused_frqu }}/{{ medicineForm.cmused_mtd }}</span>  
        </div>
        <div class="prescription-footer border-bottom-bold">
          <div class="signatures">
            <div class="signature">
              <div class="label">医师：</div>
              <div class="picture" >
                <el-image :src="signatures.doctorurl" v-if="signatures.doctorurl"></el-image>
              </div>
              
            </div>
            <div class="signature">
              <div class="label">审核药师：</div>
              <div class="picture" >
                <el-image :src="signatures.PharmacistAccessoryUrl" v-if="signatures.PharmacistAccessoryUrl" ></el-image>
              </div>
            </div>
          </div>
          <div class="drcode aic"><div class="label">医师编码：</div>{{userInfo.dr_code}}</div>
          <div class="signatures">
            <div class="signature">
              <div class="label">调配核对：</div>
              <div class="picture" >
                <el-image :src="signatures.DeployAccessoryUrl" v-if="signatures.DeployAccessoryUrl" ></el-image>
              </div>
            </div>
            <div class="signature">
              <div class="label">复核/发药：</div>
              <div class="picture" >
                <el-image :src="signatures.ReviewAccessoryUrl" v-if="signatures.ReviewAccessoryUrl" ></el-image>
              </div>
            </div>
          </div>
        </div>
        <div class="prescription-notice">
          <p>提醒： 医师处方仅开具当日有效(医师注明除外)；</p>
          <p>服用抗生素类期间以及治疗结束后72小时内，应禁止饮酒或摄入含酒精饮料；</p>
          <p>本处方针对患者本次问诊有效、限本人使用,医师处方仅开具当日有效；</p>
          <p>此处方仅限 {{ detail.fixmedins_name }} 使用。</p>
        </div>
    
        <div class="prescription-remark">
          <strong>备注：</strong> 
        </div>
    
        

      </div>
      <div class="s-foot text-center">
          <!-- <el-button class="foot-btn" type="primary" @click="transPrescription" :loading="btnLoading">{{btnText}}</el-button> -->
          <el-button class="foot-btn" type="primary" @click="close">关闭</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script setup name="prescription-dialog">
import axios from 'axios';
import {computed, nextTick, reactive, ref} from "vue";
import html2canvas from 'html2canvas';
import { useUserStore } from '@/store/user';
import {ElMessage} from "element-plus";
import dict from '@/utils/dict.js'

const props = defineProps({
  // 显示右键菜单
  OnlineInquiryId: {
    type: String,
    default: ''
  },
  medicineListProps: {
    type: Array,
    default: () => []
  },
  orderInfo: {
    type: Object,
    default: () => {}
  },
  // 中药处方配置详情
  medicineForm: {
    type: Object,
    default: () => {}
  },
  signatures: {
    type: Object,
    default: () => {}
  },
})
const userInfo = useUserStore().userInfo
const dialogVisible = ref(false)
const detail = computed(() => props.orderInfo)  //  处方订单详情
const medicineList = computed(() => props.medicineListProps)
// const signatures = ref({})

const prescriptionRef = ref(null);
const imagePreview = ref(null);
const uploadStatus = ref(null);
const btnText = ref('外部流转');
const btnLoading = ref(false);
const isPreview = ref(false);
const CirculationTypeName = computed(() => {
  if(!detail.value.CirculationType) return ''
  return dict.CirculationType.find((item) => item.value == detail.value.CirculationType)?.label
})
function show(_isPreview = false) {
  dialogVisible.value = true
  isPreview.value = _isPreview
  // getDetail()
}
const getDetail = function () {
  let params = {
    OnlineInquiryId: props.OnlineInquiryId,
  }
  sa.ajax('/api/webOnlineInquiry/onlineInquiryDetail', params, function (res) {
    // tableData.value = res.data;	// 数据
    if (res.code == '1') {
      detail.value = res.data || {}
      // signatures.value = res.data2 || {}
      // medicineList.value = res.data1 || []
    }
  })
}
// 处方流转 生成处方单
async function transPrescription() {
  return new Promise(async (resolve, reject) => { 
    try {
      // 1. 生成图片
      btnText.value ='正在生成处方单';
      btnLoading.value = true;
      // 1. 生成图片
      uploadStatus.value = { message: '正在生成图片...', error: false };

      const canvas = await html2canvas(prescriptionRef.value, {
        scale: 2, // 提高输出质量
        logging: false,
        useCORS: true,
        allowTaint: true,
        backgroundColor: '#FFFFFF' // 确保背景是白色
      });
      
      // 显示预览
      imagePreview.value = canvas.toDataURL('image/png');
      
      // 2. 转换为Blob对象
      uploadStatus.value.message = '正在准备上传数据...';
      const blob = await new Promise(resolve => {
        canvas.toBlob(resolve, 'image/png', 0.9);
      });
      
      // 3. 创建FormData并上传
      uploadStatus.value.message = '正在上传...';
      const formData = new FormData();
      const filename  = `${Date.now()}.png`;
      formData.append('file', blob, filename);
      formData.append('prescription', blob, 'prescription.png');
      formData.append('type', '43'); // 可以添加其他元数据
      
      const loginInfo = useUserStore().loginInfo || {}

      // 4. 发送到后端
      const response = await axios.post('/api/attachmentUpload/attachmentUpload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          "username": loginInfo.username || '',
          "password": loginInfo.password || '',
        }
      });
      console.log('response',response)
      if(response.data.code == '1' && response.data.data) {
        // submitPrescription(response.data.data.accessoryId)
        resolve(response.data.data.accessoryId)
      }
      uploadStatus.value = { 
        message: `上传成功！文件路径: ${response.data.filePath}`, 
        error: false 
      };
      
    } catch (error) {
      console.error('上传失败:', error);
      btnText.value ='生成失败，重新上传';
      btnLoading.value = false;
      uploadStatus.value = { 
        message: `上传失败: ${error.message || '未知错误'}`, 
        error: true 
      };
    }

  });
  
}

// 提交处方单给服务端 外部流转
async function submitPrescription(accessoryId) {
  let params = {
    accessoryId,
    OnlineInquiryNo: detail.value.OnlineInquiryNo
  }
  sa.ajax('/api/webPres/presCirculation', params, function (res) {
    btnText.value ='外部流转';
    btnLoading.value = false;
    // tableData.value = res.data;	// 数据
    if (res.code == '1') {
      close()
      ElMessage.success('开方单流转成功')
      emits('afterClose')
    }else {
      
    }
  })
}
const emits = defineEmits(['afterClose'])
function close() {
  dialogVisible.value = false
}
defineExpose({
  show,
  transPrescription
})
</script>

<style scoped lang="scss">
.hide-dialog{
  transform: translateX(-2000px);
}
.border-bottom{
  border-bottom: 1px solid #333;
}
.padding-bottom{
  padding-bottom: 10px;
}
.padding-lr-lg{
  padding-left: 60px;
  padding-right: 60px;
}
.border-bottom-bold{
  border-bottom: 2px solid #333;
}
.title{
  font-size: 26px;
  font-weight: 600;
  text-align: center;
  margin: 25px 0 20px 0;
  position: relative;
  .type{
    position: absolute;
    right: 50px;
    top: 0px;
    border: 1px solid #333;
    border-radius: 5px;
    font-size: 16px;
    padding: 5px 10px;
  }
}
.prescription-container{
  width: 595px;
  padding: 1px 50px;
  font-weight: 600;
  font-size: 14px;
  font-family: '黑体';
  color: #333;
}
.prescription-info{
  padding-bottom: 5px;
}
.prescription-info .info-row {
  margin-bottom: 0px;
  overflow: hidden;
  flex-wrap: wrap;
}
.prescription-info .info-row .flex1{
  flex: 0 0 50%;
  margin-bottom: 8px;
}

.prescription-info .label {
  margin-right: 5px;
  white-space: nowrap;
  text-align: left;
}

.prescription-info .value {
  // border-bottom: 1px solid #333;
  flex: 1;
  overflow: hidden;
}

.prescription-medicine {
  margin: 0px 40px 0px 40px;
  min-height: 280px;
  display: flex;
  flex-direction: column;
  &.ch-prescription-medicine{
    margin: 0;
    min-height: calc(280px - 31.7px);
  }
  .blank {
    flex: 1;
    display: flex;
    flex-direction: column;
    border-top: 1px solid #333;
    
    .blank-text {
      padding: 10px 0;
      text-align: center;
    }
    
    .bias-container {
      flex: 1;
      position: relative;
      overflow: hidden;
      
      .bias {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        
        &::before {
          content: "";
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          border-top: 1px solid #333;
          transform: rotate(-9deg);
          transform-origin: 0 100%;
        }
        
        &::after {
          content: "";
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          border-top: 1px solid #333;
          transform: rotate(-5deg);
          transform-origin: 100% 0;
        }
      }
    }
  }
  .ch-medicine{
    display: flex;
    flex-wrap: wrap;
    font-weight: 100;
    margin-top: 10px;
    .item{
      flex: 0 0 20%;
      margin-bottom: 20px;
      .num{
        position: relative;
        top: 8px;
        margin-left: 2px;
        white-space: nowrap;
      }
      .name{
        flex: inherit;
      }
    }
  }
}

.prescription-medicine table {
  width: 100%;
  border-collapse: collapse;
  margin: 10px 0;
}

.prescription-medicine th,
.prescription-medicine td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.prescription-medicine th {
  background-color: #f2f2f2;
}

.sig {
  font-size: 15px;
  min-height: 21px;
  padding-top: 5px;
  margin-bottom: 10px;
}

.prescription-notice {
  margin: 10px 0;
  font-size: 14px;
  color: #666;
}

.prescription-notice p {
  margin: 5px 0;
  font-size: 11px;
  font-weight: 100;
}

.prescription-remark {
  margin: 10px 0;
  font-size: 11px;
  font-weight: 100;
}

.prescription-footer {
  min-height: 50px;
  border-top: 2px solid #333;
  padding-top: 15px;
}

.signatures {
  display: flex;
  margin-bottom: 10px;
  .label{
    text-align: left;
    margin-right:20px;
  }
}

.signature {
  text-align: center;
  display: flex;
  align-items: center;
  flex: 0 0 50%;
  .picture{
    width: 70px;
    height: 30px;
  }
  
}
.drcode{
  font-weight: 100; 
  font-size: 13px;
  margin-bottom: 5px;
}
.external-flow {
  text-align: center;
  font-weight: bold;
  margin-top: 20px;
}
</style>